import React from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  TouchableHighlight,
  TouchableWithoutFeedback,
  FlatList,
  Image,
  Dimensions,
  StatusBar,
  KeyboardAvoidingView,
  TextInput,
  Alert,
  ActivityIndicator,
} from 'react-native';
import {Actions} from 'react-native-router-flux';
import CommonStyles from '../../common/styles';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import api from '../../common/api';
import {AlbumView, Overlay, PullPicker} from 'teaset';
import Toast from 'react-native-easy-toast';
import {Avatar, Divider} from 'react-native-elements';
import Button from 'antd-mobile/lib/button';
import Config from '../../common/config';
import util from '../../common/util';
import CommentList from '../../common/CommentList';

const {width, height} = Dimensions.get('window');

export default class CommentScreen extends React.Component {
  constructor(props) {
    console.log("CommentScreen: ", props);
    super(props);
    this.state = {
      orderType: null,
      params: props.router_params,
      page: 1,
      hasMore: true,
      loading: false,
      loadingMore: false,
      list: [],
      inputText: "",
    }
  }

  orderTypes = [
    '综合排序',
    '按回复时间排序',
    '按发表时间排序'
  ]

  images = {}
  thumbs = {}

  selectOrderType() {
    console.log("selectOrderType");
    PullPicker.show(
      '选择排列顺序',
      this.orderTypes,
      this.state.orderType || 0,
      (item, index) => this.setState({orderType: index})
    );
  }

  renderSectionHeader({section}) {
    if (section.content == "forum_info") {
      return null;
    }
    return (
      <View style={[CommonStyles.container]}>
        <View style={[CommonStyles.row, styles.topicFilter]}>
          <Text style={styles.topicFilterActive}>全部</Text>
      
            <TouchableOpacity style={[CommonStyles.row, styles.topicFilterOrder]} onPress={() => this.selectOrderType()}>
              <Text>回复时间排序</Text>
              <Icon name="chevron-down" size={20}/>
            </TouchableOpacity>
       
        </View>
      </View>
     
    )
  }

  componentDidMount() {
    this.setState({
      loading: true,
    }, () => {
      this.fetchComments();
    });
  }

  onRefresh() {
    this.setState({
      loading: true,
      page: 1,
      hasMore: true,
    }, () => {
      this.fetchComments();
    })
  }

  onEndReached({distanceFromEnd}) {
    console.log("onEndReached...", distanceFromEnd);
    if (this.state.loadingMore) {
      console.log("onEndReached...loadingMore...");
      return;
    }
    if (this.state.hasMore) {
      this.setState({
        loadingMore: true
      }, () => {
        this.fetchComments();
      })
      
    }
    
  }

  fetchComments() {
    var self = this;
    let queryString = "topic_key=" + this.state.params.topic.key + "&page=" + this.state.page;
    api.listComment(queryString)
    .then((response) => {
      console.log(response);
      self.setState({
        loading: false,
        loadingMore: false,
      });
      if (response.ret == 0) {
        if (response.data.pagination.count == 0) {
          console.log("count = 0, hasMore = false");
          self.setState({hasMore: false});
          return;
        }
        if (response.data.pagination.current_page == 1) {
          var newList = response.data.list;
        } else {
          var newList = [...self.state.list, ...response.data.list];
        }
        let newState = {
          list: newList,
          pagination: response.data.pagination,
          page: response.data.pagination.current_page + 1,
        }
        self.setState(newState);
      } else {
        Toast.show(response.msg);
      }
      
    })
  }

  createComment() {
    let data = {
      tid: this.state.params.topic.id,
      content: this.state.inputText,
    }
    api.createComment(data).then(response => {
      console.log(response);
      if (response.ret == 0) {
        let textInput = this.refs["create_comment_text_input"];
        
        this.setState({
          inputText: "",
          hasMore: true,
        }, () => {
          textInput.focus();
          textInput.blur();
          // this.fetchComments();
        });
      }
      this.refs.toast.show(response.msg);
    })
  }
 
  render() {
    return (
      <KeyboardAvoidingView style={{flex: 1}} behavior="padding" keyboardVerticalOffset={60}>
        <CommentList
          data={this.state.list}
          refreshing={this.state.loading}
          loadingMore={this.state.loadingMore}
          onRefresh={() => this.onRefresh()}
          onEndReached={(info) => this.onEndReached(info)}
        />
        <View style={[CommonStyles.row, styles.textInputWrap]}>
          <TextInput 
            style={styles.textInput} 
            multipline={true} 
            underlineColorAndroid="transparent" 
            onChangeText={text => this.setState({inputText: text})}
            ref="create_comment_text_input"
          
          />
          <TouchableOpacity style={styles.submitBtn} onPress={() => this.createComment()}>
            <Text style={{fontSize: 18}}>提交</Text>
          </TouchableOpacity>
        </View>
        <Toast ref="toast" position="center"/>
     </KeyboardAvoidingView>
    )
  }
}

var styles = StyleSheet.create({
  sectionTopAction: {
    paddingTop: 24,
    justifyContent: "space-between",
    alignItems: "center",
  },
  pagetTitleLeft: {
    alignSelf: "flex-start"
  },
  sectionHeaderWrapper: {
    paddingBottom: 15,
    marginBottom: 5,
  },
  sectionHeader: {
    alignItems: "center",
    justifyContent: "space-between",
  },
  forumDesc: {
    marginLeft: 10,
  }, 
  forumInfo: {
    alignItems: "center",
  },
  forumCover: {

  },
  nickname: {
    marginBottom: 5
  },
  updateTime: {
    fontSize: 12,
  },
  viewCount: {
    fontSize: 12,
  },
  commentCount: {
    fontSize: 12,
  },
  forumName: {
    fontSize: 20,
    marginBottom: 5
  },
  forumStat: {
    marginRight: 10,
  },
  followBtn: {
    width: 50,
    height: 30,
  },
  divider: {
    marginTop: 10,
    marginBottom: 10,
  },

  flatList: {
    marginTop: 4,
  },

  itemWrap: {
    marginBottom: 3,
    paddingTop: 10,
    paddingBottom: 10,
  },
  itemContentWrap: {
    paddingLeft: 34,
  },
  itemSeparator: {
    display: "flex",
    height: 1,
    backgroundColor: "#ddd"
  },
  arrow: {
    position: "absolute",
    right: 0
  },
  countWrap: {
    alignItems: "center",
    marginLeft: 5,
  },
  contentWrap: {
    paddingTop: 10,
    paddingBottom: 10,

  },
  floorWrap: {
    paddingLeft: 80,
  },
  detailAttachmentImage: {
    height: 150
  },
  topicFilter: {
    justifyContent: "space-between",
    alignItems: "center",
    paddingTop: 5,
    paddingBottom: 5,
    borderBottomColor: "#eee",
    borderBottomWidth: 1,
  },
  topicFilterActive: {
    borderBottomWidth: 1,
    borderBottomColor: "#000",
  },
  topicFilterOrder: {
    alignItems: "center",
  },
  mainFloorInfoHeader: {
    justifyContent: "space-between"
  },
  commentCommentWrap: {
    backgroundColor: "#eee",
    padding: 10,
    marginTop:10,
  },
  commentCommentContent: {
    flexWrap: "wrap",
    marginBottom: 10,
  },
  textInputWrap: {
    height: 40,
  },
  textInput: {
    width: "88%",
    padding: 10,
    textAlignVertical: "top",
    backgroundColor: "#eee",
  },
  submitBtn: {
    display: "flex",
    width: "12%",
    justifyContent: "center",
    alignItems: "center",
  },
  loadingMore: {
    paddingVertical: 20,
    borderTopWidth: 1,
    borderColor: "#CED0CE"
  }

})